<template>
    <div class="chat-container">
        <!-- 左侧历史对话 -->
        <div class="chat-history">
            <div class="new-chat" @click="createNewChat">+ 新建对话</div>
            <div class="search">
                <t-input v-model="searchValue" placeholder="搜索对话" size="small" clearable />
            </div>
            <div class="history-list">
                <div v-for="chat in filteredConversations" :key="chat.id" class="history-item"
                    :class="{ active: chat.id === currentChatId }" @click="switchChat(chat.id)">
                    {{ chat.title }}
                </div>
                <div v-if="filteredConversations.length === 0" class="no-result">
                    暂无匹配对话
                </div>
            </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="chat-message">
            <!-- 消息列表 -->
            <div class="message-list" ref="messageListRef">
                <t-chat-item v-for="(msg, index) in currentMessages" :key="index" :avatar="msg.avatar" :name="msg.name"
                    :role="msg.role" :datetime="msg.datetime" :content="msg.content" :variant="msg.variant" />
            </div>

            <!-- 输入框 -->
            <div class="chat-input">
                <t-chat-sender ref="chatSenderRef" v-model="inputValue" class="chat-sender"
                    :textarea-props="{ placeholder: '请输入消息...' }" :disabled="loading" :loading="loading"
                    @send="handleSend">
                    <!-- 发送按钮 -->
                    <template #suffix>
                        <t-button theme="primary" variant="base" size="large" :disabled="!inputValue.trim() || loading"
                            @click="handleSend">
                            发送
                        </t-button>
                    </template>

                    <!-- 前缀：模型选择 + 深度思考 -->
                    <template #prefix>
                        <div class="model-select">
                            <t-tooltip content="切换知识库" theme="primary" trigger="hover">
                                <t-select v-model="selectedModel" :options="modelOptions" value-type="object" />
                            </t-tooltip>

                            <t-button class="check-box" :class="{ 'is-active': enableDeepThinking }" variant="text"
                                @click="toggleDeepThinking">
                                <SystemSumIcon />
                                <span>工具思考</span>
                            </t-button>
                        </div>
                    </template>
                </t-chat-sender>
            </div>
        </div>
    </div>

</template>
<script setup lang="ts">
import { ref, computed, nextTick, onMounted, watch } from 'vue';
import { SystemSumIcon } from 'tdesign-icons-vue-next';

// ========== 类型定义 ==========
interface Message {
    avatar: string;
    name: string;
    role: 'user' | 'assistant' | 'model-change'; // 新增 model-change 角色
    datetime: string;
    content: string;
    variant: 'text' | 'outline' | 'base';
}

// ========== 响应式数据 ==========
const loading = ref(false);
const inputValue = ref('');
const searchValue = ref('');
const messageListRef = ref<HTMLElement | null>(null);
const currentChatId = ref<string | null>(null);

const conversations = ref<{ id: string; title: string }[]>([
    { id: '1', title: '仓库地址查询' },
    { id: '2', title: '订单查询' },
    { id: '3', title: '专家服务' },
]);

const messagesMap = ref<Record<string, Message[]>>({});

const currentMessages = computed(() => {
    if (!currentChatId.value) return [];
    return messagesMap.value[currentChatId.value] || [];
});

const modelOptions = [
    { label: '默认SB英文', value: 'sb-en' },
    { label: 'SB中文', value: 'sb-zh' },
    { label: 'BD英文', value: 'bd-en' },
    { label: 'BD中文', value: 'bd-zh' },
];
const selectedModel = ref(modelOptions[0]);

const enableDeepThinking = ref(false);
const toggleDeepThinking = () => {
    enableDeepThinking.value = !enableDeepThinking.value;
};

const filteredConversations = computed(() =>
    conversations.value.filter((chat) =>
        chat.title.toLowerCase().includes(searchValue.value.toLowerCase())
    )
);

// ========== 发送模型切换消息 ==========
const postModelChangeMessage = (modelValue: string) => {
    if (!currentChatId.value) return;

    const msg: Message = {
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg', // 注意：去掉了多余空格
        name: '自己',
        role: 'model-change',
        datetime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        content: "当前知识库：" + modelValue, // 如 'deepseek-r1'
        variant: 'text',
    };

    const chatId = currentChatId.value;
    const msgList = messagesMap.value[chatId] || [];
    messagesMap.value[chatId] = [...msgList, msg]; // 响应式更新

    nextTick(() => {
        scrollToBottom();
    });
};

// ========== 监听模型切换 ==========
watch(
    () => selectedModel.value,
    (newVal, oldVal) => {
        if (!oldVal) return; // 初始化时不触发
        if (newVal.value === oldVal.value) return; // 值未变

        postModelChangeMessage(newVal.value); // 发送 model-change 消息
    },
    { immediate: false }
);

// ========== 生命周期 ==========
onMounted(() => {
    messagesMap.value = {
        '1': [
            {
                avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
                name: '自己',
                role: 'user',
                datetime: '今天 16:38',
                content: '我可以从北京发货到你们仓库吗？',
                variant: 'text',
            },
            {
                avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
                name: 'AI 客服',
                role: 'assistant',
                datetime: '今天 16:39',
                content: '可以的，这是转运服务？你可以寄送到惠州仓，我会联系你。',
                variant: 'outline',
            },
        ],
        '2': [
            {
                avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
                name: '自己',
                role: 'user',
                datetime: '昨天 10:15',
                content: '你帮我查游戏啊DO782947192793这个订单吗，我这百年一直未更改信息？',
                variant: 'text',
            },
        ],
        '3': [],
    };

    if (conversations.value.length > 0 && !currentChatId.value) {
        currentChatId.value = conversations.value[0].id;
        nextTick(() => {
            scrollToBottom();
        });
    }
});

// ========== 方法 ==========
const switchChat = (id: string) => {
    currentChatId.value = id;
    nextTick(() => {
        scrollToBottom();
    });
};

const createNewChat = () => {
    const newId = String(Date.now());
    const newChat = { id: newId, title: '新对话' };
    conversations.value.unshift(newChat);
    messagesMap.value[newId] = [];
    currentChatId.value = newId;
    nextTick(() => {
        scrollToBottom();
    });
};

const handleSend = () => {
    if (loading.value || !inputValue.value.trim()) return;

    const userMsg: Message = {
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
        name: '自己',
        role: 'user',
        datetime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        content: inputValue.value.trim(),
        variant: 'text',
    };

    const chatId = currentChatId.value!;
    const msgList = messagesMap.value[chatId] || [];
    messagesMap.value[chatId] = [...msgList, userMsg];
    inputValue.value = '';
    loading.value = true;

    setTimeout(() => {
        const reply: Message = {
            avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
            name: '机器',
            role: 'assistant',
            datetime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
            content: `您问：“${userMsg.content}”。这是一个很好的问题！正在使用 ${selectedModel.value.label} 进行${enableDeepThinking.value ? '深度思考' : '普通'}回复...`,
            variant: 'outline',
        };
        messagesMap.value[chatId] = [...messagesMap.value[chatId], reply];
        loading.value = false;
        nextTick(() => {
            scrollToBottom();
        });
    }, 1500);
};

const scrollToBottom = () => {
    if (messageListRef.value) {
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
    }
};
</script>

<style lang="less" scoped>
.chat-container {
    display: flex;
    height: 100vh;
    font-size: 14px;
    color: #333;

    .chat-history {
        width: 260px;
        background-color: #f5f7fa;
        border-right: 1px solid #e6e8eb;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .new-chat {
            padding: 12px 16px;
            font-weight: 600;
            color: #0052d9;
            cursor: pointer;

            &:hover {
                background-color: #eef2f7;
            }
        }

        .search {
            padding: 8px 16px;
            margin-bottom: 8px;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 0 8px;

            .history-item {
                padding: 10px 12px;
                border-radius: 6px;
                margin-bottom: 4px;
                cursor: pointer;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;

                &.active {
                    background-color: #e1ebf6;
                    color: #0052d9;
                    font-weight: 500;
                }

                &:hover:not(.active) {
                    background-color: #eef2f7;
                }
            }

            .no-result {
                padding: 12px;
                color: #999;
                font-size: 13px;
                text-align: center;
            }
        }
    }

    .chat-message {
        flex: 1;
        display: flex;
        flex-direction: column;
        background-color: #fff;

        .message-list {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .chat-input {
            border-top: 1px solid #e6e8eb;
            padding: 12px 16px;
            background-color: #fff;

            .model-select {
                display: flex;
                align-items: center;
                gap: 8px;

                .t-select {
                    width: 230px;
                }

                .check-box {
                    font-size: 13px;
                    color: #666;

                    &.is-active {
                        color: #0052d9;
                        font-weight: 500;
                    }

                    span {
                        margin-left: 4px;
                    }
                }
            }
        }
    }
}

// 响应式适配（可选）
@media (max-width: 768px) {
    .chat-container {
        flex-direction: column;

        .chat-history {
            width: auto;
            border-right: none;
            border-bottom: 1px solid #e6e8eb;
            height: 200px;
        }
    }
}
</style>